﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace s7nck
{
  public  class LdMachine
    {
        private bool connectStatus;
        private bool startStatus;
        private string ip;
        private string  port;
        private string machineName;
        private ConcurrentDictionary<string, string> cache = new ConcurrentDictionary<string, string>();
        private Socket ncksocket =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
        private System.Threading.Timer _timer;
        private string _guid;
        private Dictionary<string, Dictionary<string, Dictionary<string, string>>> _dict = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();

        public bool ConnectStatus { get => connectStatus; set => connectStatus = value; }
        public string Ip { get => ip; set => ip = value; }
        public string Port { get => port; set => port = value; }
        public string MachineName { get => machineName; set => machineName = value; }
        public ConcurrentDictionary<string, string> Cache { get => cache; set => cache = value; }
        public Socket Ncksocket { get => ncksocket; set => ncksocket = value; }
        public Timer Timer { get => _timer; set => _timer = value; }
        public string Guid { get => _guid; set => _guid = value; }
        public Dictionary<string, Dictionary<string, Dictionary<string, string>>> Dict { get => _dict; set => _dict = value; }
        public bool StartStatus { get => startStatus; set => startStatus = value; }

        public   LdMachine()
        {
           Cache.TryAdd("mode", "0");
            Cache.TryAdd("execution", "0");
            Cache.TryAdd("program", "0");
            Cache.TryAdd("pathFeedrate", "0");
            Cache.TryAdd("pathSvalue", "0");
            Cache.TryAdd("feedOvr", "0");
            Cache.TryAdd("speedOvr", "0");


        }

        //
        public string createGuid()
        {
            return System.Guid.NewGuid().ToString();
        }

        //连接
        public void connectMachine()
        {
            //socket连接
            Ncksocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                Ncksocket.Connect(ip, Convert.ToInt32(port));

           

            //s7协议握手
            //s7 握手
            byte[] s1 = new byte[] { 3, 0, 0, 0x16, 0x11, 0xe0, 0, 0, 04, 0x30, 0, 0xc1, 2, 4, 0, 0xc2, 02, 0x03, 03, 0xc0, 01, 0x0a };
            Ncksocket.Send(s1, s1.Length, SocketFlags.None);
            /* int   byteCount1 = socketSend.Receive(bytes, 0, socketSend.Available,
                                  SocketFlags.None);*/
            byte[] message1 = Class1.receibeMessage(Ncksocket, 22);
            StringBuilder text = new StringBuilder();
            for (int i = 0; i < message1.Length; i++)
            {
                text.Append(message1[i].ToString("x2"));
                text.Append("-");
            }
            Console.WriteLine("接受的内容-----" + text.ToString() + "-----");

            byte[] ss = new byte[] { 3, 0, 0, 0x19, 2, 0xf0, 0x80, 0x32, 1, 0, 0, 0, 1, 0, 8, 0, 0, 0xf0, 0, 0, 0x64, 0, 0x64, 03, 0xc0 };
            Ncksocket.Send(ss, ss.Length, SocketFlags.None);


            byte[] message2 = Class1.receibeMessage(Ncksocket, 25);
            StringBuilder text2 = new StringBuilder();
            for (int i = 0; i < message2.Length; i++)
            {
                text2.Append(message2[i].ToString("x2"));
                text2.Append("-");
            }
            Console.WriteLine("接受的内容-----" + text2.ToString() + "-----");


            // MessageBox.Show("连接成功！！！"+byteCount1+" "+byteCount2);
            Console.WriteLine("连接成功！！！" + message1.Length + " "/* + message2.Length*/);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);

            }
        }

        //read
        public string readData(byte[] cmd,int receiveLen,string dataType)
        {


            string dataResult="";
            try
            {
                if (ncksocket.Connected)
                {
                    ncksocket.Send(cmd, cmd.Length, SocketFlags.None);

                }
                else
                {
                    return dataResult;
                }



                byte[] cmdResult = Class1.receibeMessage(ncksocket, receiveLen);
            byte[] resultBytes = Commons.getbytes(cmdResult, 25);
            switch (dataType)
            {
                case "short": dataResult = BitConverter.ToInt16(resultBytes, 0).ToString();
                    break;
                case "string":
                    string programValue = Encoding.ASCII.GetString(resultBytes);
                    //切割掉"?"部分
                   // string[] programValueBytes = programValue.Split('/');
                  //  string programValue3 = programValueBytes[3];
                    dataResult = programValue;
                    break;
                case "double":
                    dataResult = BitConverter.ToDouble(resultBytes, 0).ToString();
                    break;
                case "int":
                    dataResult = BitConverter.ToInt32(resultBytes, 0).ToString();
                    break;
                default:
                    break;
            }
            }
            catch (Exception ex)
            {

                LogHelper.WriteLog(ex.Message, ex);
            }
            return dataResult;
        }

    }
}
